import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';

class WebHtmlPage extends StatefulWidget {
  const WebHtmlPage({Key? key}) : super(key: key);

  @override
  _WebHtmlPageState createState() => _WebHtmlPageState();
}

class _WebHtmlPageState extends State<WebHtmlPage> {
  InAppWebViewController? webViewController;

  String url = "";
  String title = "";
  int progress = 0;

  @override
  void initState() {
    super.initState();
    url = Get.arguments["url"];
    title = Get.arguments["title"];
  }

  /*
   * 注册javascript的
   */
  void initJavascript() {
    webViewController?.addJavaScriptHandler(
      handlerName: "html_slide_bottom",
      callback: (args) {
        Get.snackbar("提示", "已经滑动到底部");
        return {"result": "已经接受到了"};
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Stack(
        children: [
          InAppWebView(
              initialUrlRequest: URLRequest(url: Uri.parse(url)),
              initialOptions: InAppWebViewGroupOptions(
                crossPlatform: InAppWebViewOptions(
                  javaScriptEnabled: true,
                  mediaPlaybackRequiresUserGesture: false,
                  javaScriptCanOpenWindowsAutomatically: true,
                ),
                android: AndroidInAppWebViewOptions(
                  supportMultipleWindows: true,
                ),
              ),
              onWebViewCreated: (controller) {
                webViewController = controller;
                initJavascript();
              },
              onLoadStart: (controller, url) {},
              onLoadStop: (controller, url) {},
              onLoadError: (controller, url, code, message) {},
              onProgressChanged: (controller, progress) {
                setState(() {
                  this.progress = progress;
                });
              },
              androidOnPermissionRequest: (InAppWebViewController controller,
                  String origin, List<String> resources) async {
                return PermissionRequestResponse(
                    resources: resources,
                    action: PermissionRequestResponseAction.GRANT);
              }),
          progress < 1.0
              ? LinearProgressIndicator(
                  value: progress.toDouble(),
                  minHeight: 20,
                  color: Colors.amber,
                )
              : Container(),
        ],
      ),
    );
  }
}
